package com.wawayaya.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.view.View;

import cz.msebera.android.httpclient.Header;
import de.greenrobot.event.EventBus;
import wawayaya.kids_iread.R;

import com.creative.accountsdk.DataCenter;
import com.creative.accountsdk.OnLoginListener;
import com.creative.accountsdk.UserData;
import com.creative.accountsdk.net.XHttpHandler;
import com.creative.accountsdk.net.account.AnonProtocol;
import com.loopj.android.http.RequestHandle;
import com.wawayaya.AppContext;
import com.wawayaya.api.ApiResponseData;
import com.wawayaya.api.interf.ApiResponseJsonListener;
import com.wawayaya.api.remote.ApiConstans;
import com.wawayaya.api.remote.ApiWawayaya;
import com.wawayaya.base.BaseActivity;
import com.wawayaya.base.BaseFragment;
import com.wawayaya.cache.UserDataCache;
import com.wawayaya.db.bookshelf.RequestThread;
import com.wawayaya.fragment.ExploreFragment;
import com.wawayaya.fragment.HomeFragment;
import com.wawayaya.fragment.MyLibraryFragment;
import com.wawayaya.manager.TitleBarManager;
import com.wawayaya.util.Constants;
import com.wawayaya.util.PreferenceUtils;
import com.wawayaya.util.TLog;
import com.wawayaya.util.UIHelper;
import com.wawayaya.manager.UiFragmentManager;
import com.wawayaya.util.event.ShelfEvent;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * MainActivity
 *
 * @author David
 * @version 1.0
 * @created 2015-11-3
 */
public class MainActivity extends BaseActivity implements ApiResponseJsonListener {

    private final String TAG = getClass().getSimpleName();
    private UiFragmentManager uiManager;
    private TitleBarManager titleBarManager;
    private FragmentManager mFragmentManager;
    private BaseFragment currentFragment;   //当前Fragment
    private long lastTimeClick;
    Bundle bundle;

    //请求数据
    private RequestThread requestData;

    public static int REQUEST_CODE_OPENACCOUNT = 101;  //用于回调result处理

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            TLog.log("返回的数据。。。。。。。。what:" + msg.what);
            switch (msg.what) {
                case RequestThread.endData:
                    TLog.log("first request complete:" + msg.what);

                    break;
            }
        }
    };

    @Override
    protected void init(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);

        this.requestData();

        //网络请求
        requestData = new RequestThread(context, handler);
        requestData.start();

        mFragmentManager = getSupportFragmentManager();
        TLog.log("TASG,", " 创建 MainActivity onCreate");
        if (currentFragment == null) {
            currentFragment = new HomeFragment(requestData);
        } else {
            //不等于null，get出来   参数2：之前保存的fragment的id
            currentFragment = (BaseFragment) mFragmentManager.getFragment(savedInstanceState, "MainCurrentFragment");
        }

    }

    @Override
    public void initView() {
        //获取Fragment切换管理对象
        uiManager = UiFragmentManager.getInstance();
        uiManager.changeFragment((Class<? extends BaseFragment>) ((Object) currentFragment).getClass(), mFragmentManager, requestData);
    }

    @Override
    public void initData() {
        PreferenceUtils.putBoolean(MainActivity.this, "firstOpen", false);
        titleBarManager = TitleBarManager.getInstance();
        titleBarManager.init(MainActivity.this);

        uiManager.addObserver(titleBarManager);
        refreshPrentTeache();
    }

    @Override
    public void setListener() {
    }

    @Override
    public void onClick(View v) {

    }

    public void onClickHome(View view) {
        continueClick();
        uiManager.changeFragment(HomeFragment.class, mFragmentManager, requestData);
    }

    public void onClickExplore(View view) {
        continueClick();
        uiManager.changeFragment(ExploreFragment.class, mFragmentManager, requestData);
    }

    public void onClickMyLibrary(View viewe) {
        uiManager.changeFragment(MyLibraryFragment.class, mFragmentManager, requestData);
    }

    public void onClickSetting(View view) {
        continueClick();
        TLog.log("是否已经登陆 ：" + UserDataCache.getInstance().isLogin());
        if (UserDataCache.getInstance().isLogin() && UserDataCache.getInstance().isDevice == 0) {
            UIHelper.showSettingActivity(context);
        } else {
            accountLogin(REQUEST_CODE_OPENACCOUNT);
        }
    }

    public void onClickTeacherParent(View view) {
        continueClick();
        //UIHelper.showTeacherParentActivity(context);
        UIHelper.showTpSelectBookActivity(context);
    }

    /**
     * //防止因为卡顿现象，频繁点击导致错误
     */
    private void continueClick() {
        long time = System.currentTimeMillis();
        if (time - lastTimeClick < Constants.CLICK_INTERVAL) {
            return;
        }
        lastTimeClick = time;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        // Log.e("TASG,", "删除MainActity");
    }

    /**
     * 根据一账通用户角色判断是否显示家长中心/教师中心
     */
    private void refreshPrentTeache() {
        titleBarManager.showParentTeacher(UserData.getInstance().getRole());
    }

    private void refreshHomeFragment() {
        ShelfEvent event = new ShelfEvent(ShelfEvent.refreshIndexData);
        EventBus.getDefault().post(event);
    }

    /**
     * event回调 刷新titleBar
     *
     * @param event
     */
    public void onEvent(ShelfEvent event) {
        TLog.log("event = " + event.eventType);
        if (event.eventType == ShelfEvent.refreshParentIcon) {
            TLog.log("刷新了 event = " + event.eventType);
            refreshPrentTeache();
        }
    }

    @Override
    public void success1(ApiResponseData result) {
        if (result.getRquestType() == ApiConstans.USER_LOGIN) {
            if (isGuest) {
                saveJoyreaderResponse(result, 1, false);
            } else {
                saveJoyreaderResponse(result, 0, true);
                refreshPrentTeache();
            }
        } else if (result.getRquestType() == ApiConstans.LOGINJOYREADER) {
            saveJoyreaderResponse(result, UserDataCache.getInstance().getIsDevice(), true);
        }
        // 得到最新的登陆数据后加首页数据
        refreshHomeFragment();
    }

    @Override
    public void success0(ApiResponseData result) {
        // 得到最新的登陆数据后加首页数据
        refreshHomeFragment();
    }

    @Override
    public void error(ApiResponseData result) {
        // 得到最新的登陆数据后加首页数据
        refreshHomeFragment();
    }

    /**
     * 调用一账通sdk进行登陆
     *
     * @param requestcode
     * @return
     */
    private boolean accountLogin(int requestcode) {
        AppContext.accountSdk.removeSdk(context);
        isGuest = false;
        return AppContext.accountSdk.login(this, requestcode, new OnLoginListener() {
            @Override
            public void onError(Exception e) {
                AppContext.accountSdk.removeSdk(context);
                TLog.log("onError");
                isGuest = true;
            }

            @Override
            public void onComplete(JSONObject jsonObject) {
                TLog.log("tag onKeyShare", "accountSdk onComplete platform.....name: else  33333 UserDataCache.getInstance().exist() ");
                //存储一账通用户数据
                UserData.getInstance().save(jsonObject, context);
                ApiWawayaya.userLogin(context, jsonObject, MainActivity.this);
                isGuest = false;
            }

            @Override
            public void onCancel() {
                TLog.log("onCancel");
            }
        });
    }

    /**
     * 存储 joyreader 用户数据
     *
     * @param result
     */
    private void saveJoyreaderResponse(ApiResponseData result, int isDevice, boolean isLogin) {
        TLog.log(TAG, ".....isDevice....:" + isDevice);
        JSONObject jo = result.getRetinfo();
        if (null == jo) {
            return;
        }
        isGuest = false;
        try {
            jo.put("success", isLogin);
            jo.put("isDevice", isDevice);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        UserDataCache.getInstance().save(jo, context);

        //UmsAgent.onEvent(context, "SignIn_clk_btn_login");
        //获取joyreader 所有基础数据
        //requestData.getcHandler().sendEmptyMessage(ApiConstans.CONFIG);
    }

    /**
     * 判断是否已经登陆
     * 1. 从未登陆过，用游客身份先进行 登陆,登陆后调用  joyreader login
     * 2. 已经登陆过, 调用 joyreader中 loginJoyReader刷新用户信息
     */
    private void requestData() {
        if (null == UserDataCache.getInstance().getUserinfor()) {  //从未登陆过，用游客身份先进行 登陆
            this.guestLogin();
        } else {            //已经登陆过则调用 loginJoyReader进行登陆刷新用户信息
            //调用joyreader进行登陆
            ApiWawayaya.loginJoyReader(context, MainActivity.this);
        }
    }

    private boolean isGuest = true;

    /**
     * 游客登陆
     * 1. 一账通                    guest anon 登陆
     * 2. joyreader 使用一账通登陆   user/login
     */
    private void guestLogin() {
        isGuest = true;
        //1. 一账通      guest anon 登陆
        final AnonProtocol protocol = new AnonProtocol();
        protocol.debugUrl(DataCenter.getHttpClient());
        DataCenter.getHttpClient().post(protocol.getUrl(), protocol.getParams(), new XHttpHandler(context) {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                TLog.log(TAG, "游客登陆返回数据:" + response);
                if (protocol.parse(response, context)) {
                    UserData.getInstance().save(protocol.jsonUser, context);
                    //调用joyreader进行登陆
                    ApiWawayaya.userLogin(context, protocol.jsonUser, MainActivity.this);
                    isGuest = true;
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                isGuest = true;
            }
        });
    }

    public RequestThread getRequestData() {
        return requestData;
    }
}
